<template>
  <div class="app-container">
    <el-dialog :title="title" :visible.sync="visible" width="700px" v-if="visible" append-to-body
      :close-on-click-modal="false" @close="closeDialog">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" :label-width="labelWidth" :disabled="disabled"
        v-loading="loading">
        <el-form-item label="权益名称" prop="name">
          <el-input v-model="ruleForm.name" maxlength="20" placeholder="请输入券码名称" :style="{width: inputWidth}">
          </el-input>
        </el-form-item>
        <el-form-item label="权益类型" prop="type">
          <el-select filterable v-model="ruleForm.type" placeholder="请选择" :style="{width: inputWidth}"
            :disabled="ruleForm.id == null?false:true">
            <el-option v-for="item in options" :key="item.id" :label="item.value" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-if="ruleForm.type==2">
          <el-form-item label="生成数量" prop="total">
            <el-input v-model="ruleForm.total" maxlength="20" placeholder="请输入生成数量" :style="{width: inputWidth}"
              :disabled="ruleForm.id == null?false:true">
            </el-input>
          </el-form-item>
          <el-form-item label="核销店铺：" prop="shopIdList">
            <el-select v-model="ruleForm.shopIdList" multiple placeholder="请选择" filterable clearable
              :style="{width: inputWidth}">
              <el-option v-for="(item,index) in shopList" :key="index" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="二维码有效期：" prop="validityType">
            <el-radio-group v-model="ruleForm.validityType" @change="couponValidityTypeChange">
              <el-form-item label="" prop="">
                <el-radio :label="'1'">不限时间</el-radio>
              </el-form-item>
              <template>
                <el-form-item label="" prop="validityDay" ref="validityDayRef">
                  <el-radio :label="'2'">
                    <span>购券之日起</span>
                    <el-input v-model="ruleForm.validityDay" :disabled="ruleForm.validityType=='2'?false:true"
                      placeholder="请输入" style="width: 320px;margin: 0 6px 0px">
                    </el-input>
                    <span>天内有效</span>
                  </el-radio>
                </el-form-item>
              </template>
              <template>
                <el-form-item label="" prop="validityDate" ref="validityDateRef">
                  <el-radio :label="'3'">
                    <span style="margin-right: 6px">生效时间段</span>
                    <el-date-picker v-model="ruleForm.validityDate" type="datetimerange"
                      value-format="yyyy-MM-dd HH:mm:ss" style="margin: 14px 0 0px;width:380px"
                      format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                      :clearable="false" :disabled="ruleForm.validityType=='3'?false:true" @input="$forceUpdate()"
                      @change="timeChange">
                    </el-date-picker>
                  </el-radio>
                </el-form-item>
              </template>
            </el-radio-group>
          </el-form-item>
        </div>
        <el-form-item label="权益说明" prop="notes">
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6}" v-model="ruleForm.notes"
            placeholder="请输入权益说明或者使用方式等内容" :style="{width: inputWidth}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="sumitLoading">确认生成</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addInventory,
    updateInventory,
    getInventory,
    adminDict,
    shopSelect,
  } from "@/api/equityManager/equityInventory";

  export default {
    name: "Dialog",
    data() {
      var checkTotal = (rule, value, callback) => { //券有效期限制时间校验
        let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
        // console.log(value, this.ruleForm.couponValidityType)
        if (!value) {
          return callback(new Error('请输入'));
        } else if (regNumber.test(value) == false) {
          return callback(new Error('请输入大于0正整数'));
        } else {
          return callback()
        }
      };
      var checkValidityDay = (rule, value, callback) => { //券有效期限制时间校验
        let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
        // console.log(value, this.ruleForm.couponValidityType)
        if (!value && this.ruleForm.validityType == '2') {
          return callback(new Error('请输入'));
        } else if (regNumber.test(value) == false && this.ruleForm.validityType == '2') {
          return callback(new Error('请输入大于0正整数'));
        } else {
          return callback()
        }
      };
      var checkValidityDate = (rule, value, callback) => { //生成时间段时间校验
        console.log('时间段'+value)
         console.log('时间段2'+this.ruleForm.validityDate)
        if (this.ruleForm.validityDate != undefined && this.ruleForm.validityDate.length == 0 && this.ruleForm.validityType == '3') {
          return callback(new Error('请选择生效时间段'));
        } else if (this.ruleForm.validityDate == '' && this.ruleForm.validityType == '3') {
          return callback(new Error('请选择生效时间段'));
        } else {
          return callback()
        }
      };
      return {
        labelWidth: '120px',
        inputWidth: '480px',
        sumitLoading: false,
        loading: false,
        // 是否禁用表单
        disabled: false,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        visible: false,
        // 店铺数组
        options: [],
        // 表单参数
        ruleForm: {
          id: '', //权益库存id
          name: '', //	权益名称
          type: '', //权益类型  1导入券码 2系统生成 equity_inventory_type
          notes: '', //权益说明
          shopIdList: [], //核销店铺id
          total: '', //生成数量
          validityDay: '', //二维码有效天数
          validityEndTime: '', //二维码生效结束时间
          validityStartTime: '', //二维码生效开始时间
          validityType: '1', //二维码有效期类型 1 不限 2间隔天数 3 指定时间
          validityDate: [], //生效时间 (校验用)
        },
        shopList: [], //店铺列表
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "请输入券码名称",
            trigger: ['blur', 'change'],
          }],
          type: [{
            required: true,
            message: "请选择权益类型",
            trigger: 'change',
          }],
          notes: [{
            required: true,
            message: "请输入权益说明",
            trigger: ['blur', 'change'],
          }],
          total: [{
            required: true,
            validator: checkTotal,
            trigger: ['blur', 'change'],
          }],
          shopIdList: [{
            required: true,
            message: "请选择核销店铺",
            // validator: checkNum,
            trigger: ["change"]
          }],
          validityType: [{
            required: true,
            message: "请选择二维码有效期",
            // validator: checkNum,
            trigger: ["change"]
          }],
          validityDay: [{ //间隔天数
            validator: checkValidityDay,
            trigger: ['change', 'bulr'],
          }],
          validityDate: [{ //指定时间
            validator: checkValidityDate,
            // type: 'array',
            // required: true,
            // message: '请选择生效时间',
            trigger: 'change'
          }, ],
        }
      };
    },
    created() {

    },
    methods: {
      /** 弹框 */
      open(id) {
        if (id == null) {
          this.ruleForm.id = null
          this.title = '新增权益券码'
        } else {
          this.ruleForm.id = id
          this.title = '编辑权益券码'
          this.getInventory()
        }
        this.getadminDict()
        this.getShopSelect()
        this.visible = true
      },
      getadminDict() {
        //获取权益类型字典
        const params = {
          dictType: "equity_inventory_type",
        };
        adminDict(params).then((res) => {
          this.options = res.result[0].dictList;
        });
      },
      getShopSelect() { //获取核销店铺下拉
        const params = {
          type: '2',
        };
        shopSelect(params).then((res) => {
          this.shopList = res.result;
        });
      },
      /** 获取权益库存信息 */
      getInventory() {
        this.loading = true
        getInventory(this.ruleForm.id).then(res => {
          this.loading = false
          this.ruleForm = res.result
          if (this.ruleForm.validityStartTime != '') {
            this.ruleForm.validityDate = [this.ruleForm.validityStartTime, this.ruleForm.validityEndTime]
          } else {
            this.ruleForm.validityDate = []
          }
        }).catch(() => {

        });
      },
      //二维码有效期选择
      couponValidityTypeChange(e) {
        if (e == 1) {
          this.$refs['validityDayRef'].clearValidate();
          this.$refs['validityDateRef'].clearValidate();
        } else if (e == 2) {
          this.$refs['validityDateRef'].clearValidate();
        } else if (e == 3) {
          this.$refs['validityDayRef'].clearValidate();
        }
      },
      timeChange(e) {
        this.ruleForm.validityDate = e
        this.$set(this.ruleForm,'validityDate',e)
        this.$refs['validityDateRef'].clearValidate();
        if (e == null) {
          this.ruleForm.validityDate = []
          this.ruleForm.validityStartTime = ''
          this.ruleForm.validityEndTime = ''
        }
      },
      inputClick() { //修复input无法输入问题
        this.$forceUpdate()
      },
      /** 重置表单 */
      reset() {
        console.log('取消')
        this.$refs['ruleForm'].resetFields()
        this.ruleForm = {
          id: '', //权益库存id
          name: '', //	权益名称
          type: '', //权益类型  1导入券码 2系统生成 equity_inventory_type
          notes: '', //权益说明
          shopIdList: [], //核销店铺id
          total: '', //生成数量
          validityDay: '', //二维码有效天数
          validityEndTime: '', //二维码生效结束时间
          validityStartTime: '', //二维码生效开始时间
          validityType: '1', //二维码有效期类型 1 不限 2间隔天数 3 指定时间
          validityDate: [], //生效时间 (校验用)
        }
      },
      // 取消按钮
      cancel() {
        this.visible = false;
        this.reset()
      },
      closeDialog() { //关闭弹窗
        this.reset()
      },
      /** 提交按钮 */
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.sumitLoading = true
            if (this.ruleForm.validityDate != undefined && this.ruleForm.validityDate.length != 0) {
              this.ruleForm.validityStartTime = this.ruleForm.validityDate[0]
              this.ruleForm.validityEndTime = this.ruleForm.validityDate[1]
            }
            if (this.ruleForm.id != null) {
              updateInventory(this.ruleForm).then(response => {
                this.$message.success('修改成功');
                this.cancel();
                this.$emit('refresh')
                this.sumitLoading = false
              }).catch(() => {
                this.sumitLoading = false
              });
            } else {
              addInventory(this.ruleForm).then(response => {
                this.$message.success('新增成功');
                this.cancel();
                this.$emit('refresh')
                this.sumitLoading = false
              }).catch(() => {
                this.sumitLoading = false
              });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    }
  };

</script>
<style scoped>
  .from_box {
    margin: 20px 0 0;
  }

  .shop_name {
    font-weight: bold;
    font-size: 16px;
    color: #1890FF;
    margin-bottom: 30px;
  }

  .input_box {
    margin: 0 10px;
  }

  .el_radio_box {
    display: flex;
    flex-direction: column;
  }

  .el_radio_box .el-radio {
    margin-top: 12px;
  }

</style>
